var express = require("express");
var router = express.Router();
const moment = require("moment");
const AccountModel = require("../../models/AccountModel");

// 获取全部账单
router.get("/account", async function (req, res, next) {
  AccountModel.find()
    .sort({ time: -1 })
    .exec((err, data) => {
      if (err) {
        return res.json({
          code: "1001",
          msg: "读取失败",
          data: null,
        });
      }
      //响应成功的提示
      res.json({
        code: "0000",
        msg: "读取成功",
        data: data,
      });
    });
});

// 新增账单
router.post("/account", function (req, res, next) {
  console.log(req.body);

  AccountModel.create(
    {
      ...req.body,
      // 字符串转对象，对象转时间对象
      time: moment(req.body.time).toDate(),
    },
    (err) => {
      if (err) {
        return res.json({
          code: "1001",
          msg: "创建失败",
          data: null,
        });
      }

      res.json({
        code: "0000",
        msg: "创建成功",
        data: null,
      });
    }
  );
});

// 删除账单
router.delete("/account/:id", function (req, res, next) {
  // mongodb内部会间将_id赋值给一个隐藏的id字段
  const id = req.params.id;
  AccountModel.deleteOne({ id }, (err) => {
    if (err) {
      return res.json({
        code: "1001",
        msg: "删除失败",
        data: null,
      });
    }

    res.json({
      code: "0000",
      msg: "删除成功",
      data: null,
    });
  });
});

// 获取单个账单
router.get("/account/:id", function (req, res, next) {
  const { id } = req.params;
  if (!id) {
    return res.json({
      code: "1001",
      msg: "params id为空",
      data: null,
    });
  }

  AccountModel.find({ id }, (err, data) => {
    if (err) {
      return res.json({
        code: "1003",
        msg: "查询失败",
        data: null,
      });
    }

    res.json({
      code: "0000",
      msg: "查询成功",
      data: data[0],
    });
  });
});

// 更新账单信息
router.patch("/account/:id", function (req, res, next) {
  const { id } = req.params;
  if (!id) {
    return res.json({
      code: "1001",
      msg: "params id为空",
      data: null,
    });
  }

  AccountModel.updateOne({ id }, { ...req.body }, (err, data) => {
    if (err) {
      return res.json({
        code: "1003",
        msg: "更新失败",
        data: null,
      });
    }

    // 再次查询数据库
    AccountModel.findById(id, (err1, data1) => {
      if (err1) {
        return res.json({
          code: "1003",
          msg: "读取失败",
          data: null,
        });
      }
      res.json({
        code: "0000",
        msg: "更新成功",
        data: data1,
      });
    });
  });
});

module.exports = router;
